/**
 *
 * Copyright 2015 RSVP Technologies Inc. All rights reserved.
 * LockExample.java
 *
 */
package com.gfinal.concurrent;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Gao Yudong (gyd@nbicc.com)
 * @date 2015-3-6
 */
public class LockExample {
	private final Lock lock = new ReentrantLock();
	private final Condition empty = lock.newCondition();
	private Map<Integer, String> map = new HashMap<Integer, String>();

	public LockExample() {

	}

	public String read(Integer id) {
		lock.lock();
		String info = null;
		try {
			while (null == (info = map.get(id))) {
				empty.await();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
		return info;
	}
	
	public void write(Integer id, String value) {
		lock.lock();
		try {
		    map.put(id, value);
		    empty.signalAll();
		} finally {
		    lock.unlock();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		final LockExample lock = new LockExample();
		ExecutorService exec = Executors.newSingleThreadExecutor();
		Scanner sc = new Scanner(System.in);
		String input = null;
		exec.execute(new Runnable() {

			@Override
			public void run() {
				for(int i = 0; i < 100; i++) {
					System.out.println("start:" + i);
					String name = lock.read(i);
					System.out.println("output:" + name);
				}
			}
			
		});
		
		do {
			input = sc.nextLine();
			String[] s;
			try {
				s = input.split(",");
				lock.write(Integer.valueOf(s[0]), s[1]);
			} catch (Exception e) {
				
			}
		} while(!input.equalsIgnoreCase("end"));
		
		
	}

}
